package com.wmx.array;

public class MyArray {
    private Long [] arr;
    private int size;

    MyArray(){
        arr = new Long[50];
    }

    MyArray(int maxSize){
        arr = new Long[maxSize];
    }

    /*
    插入数组
    */
    public void  add(Long value){
        arr[size] = value;
        size++;
    };

    /*
    * 添加有序数组 小到大
    * */
    public void  addOrderlyAsc(Long value){
        int i;
        for(i=0;i<size;i++){
            if(arr[i]>value){
                break;
            }
        }

        for (int j = size ;j>i ;j--){
            arr[j] = arr[j-1];
        }

        arr[i] = value;
        size++;
    }


    /*
    * 添加有序数组 大到小
    * */
    public void  addOrderlyDesc(Long value){
        int i;

        for(i=0;i<size;i++){
            if(arr[i]<value){
                break;
            }
        }

        for (int j = i ;j< size ;j++){
            arr[j+1] = arr[j];
        }

        arr[i] = value;
        size++;
    }

    /**
     * 删除
     */

    public void delete(Long value){
        for (int i = 0 ;i<size;i++){
            if(arr[i]==value){
                arr[i] = arr[i+1];
                break;
            }

        }
        size--;
    }


    /**
     * 显示数组中数据
     */
    public void display(){
        StringBuffer stringBuffer = new StringBuffer();
        stringBuffer.append("[");
        for (int i = 0 ;i<size;i++){
            stringBuffer.append(arr[i]);
            if(i==size-1){
                stringBuffer.append("");
            }else {

                stringBuffer.append(",");
            }
        }
        stringBuffer.append("]");
        System.out.println(stringBuffer.toString());
    };


    /*
    *二分法查找
    * */

    public int binarySearch(Long value){
        int low = 0;
        int pow =size-1;
        while (true){
            int middle = (low + pow ) /2;
            if(arr[middle]==value){
                return middle;
            }else if(low>pow){
                return -1;

            }else {
                if(arr[middle]>value){
                    pow = middle-1;
                }else {
                    low = middle+1;
                }
            }
        }
    }


}
